/*
 * @Author: cl
 * @Description:
 * @Date: 2023-04-07 10:23:48
 * @LastEditTime: 2023-04-13 11:37:53
 * @FilePath: \jsnode\nestjs\naota\src\tiger\tiger.service.ts
 * @LastEditors: cl
 */
import { Injectable } from '@nestjs/common'
import { CreateTigerDto } from './dto/create-tiger.dto'
import { UpdateTigerDto } from './dto/update-tiger.dto'
import { Tiger } from './entities/tiger.entity'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { Son } from './entities/son.entity'
import { log } from 'console'

@Injectable()
export class TigerService {
  constructor(
    @InjectRepository(Tiger) private readonly tiger: Repository<Tiger>,
    @InjectRepository(Son) private readonly son: Repository<Son>,
  ) {}

  create(createTigerDto: CreateTigerDto) {
    const data = new Tiger()
    data.name = createTigerDto.name
    data.age = createTigerDto.age
    data.sex = createTigerDto.sex
    data.sons = createTigerDto.sons
    return this.tiger.save(data)
  }

  async addSons(params: { sons: string[]; tigerId: number }) {
    const tiger = await this.tiger.findOne({ where: { id: params.tigerId } })
    const sons: Son[] = []
    // if (params.sons?.length > 0) {
    //   params.sons.forEach(async (item) => {
    //     let son = new Son();
    //     son.name = item;
    //     await this.son.save(son);
    //     sons.push(son);
    //   });
    //   console.log(sons);

    // }
    // for (let i = 0; i < params.sons.length; i++) {
    //   let T = new Son();
    //   T.name = params.sons[i];
    //   await this.son.save(T);
    //   sons.push(T);
    // }

    for (const item in params.sons) {
      const T = new Son()
      T.name = params.sons[item]
      await this.son.save(T)
      sons.push(T)
    }
    //es6推荐
    // for(let item of params.sons){
    //   let T = new Son();
    //   T.name = item;
    //   await this.son.save(T);
    //   sons.push(T);
    // }

    console.log('-------', sons)
    tiger.sons = sons
    console.log('result:', tiger)
    return this.tiger.save(tiger)
  }

  async findPostOne(params: { tigerId: number }) {
    const tiger = await this.tiger.findOne({ where: { id: params.tigerId } })
    console.log(tiger)
    return tiger
  }
  async findAll() {
    const list = await this.tiger.find()
    return list
  }

  findOne(id: string) {
    return `This action returns a #${id} tiger`
  }

  update(id: number, updateTigerDto: UpdateTigerDto) {
    return `This action updates a #${id} tiger`
  }

  remove(id: number) {
    return `This action removes a #${id} tiger`
  }

  findBlackOne(name: string, age: number) {
    return `This action findBlackOne a #${name}${age} blacktiger`
  }
}
